package com.iplant.ams.serviceImpl.dao.dms.scada;

import com.iplant.ams.service.po.dms.DMSDeviceLedger;
import com.iplant.ams.service.po.dms.scada.alarm.*;
import com.iplant.ams.service.po.dms.scada.para.DMSDeviceRealParameter;
import com.iplant.ams.serviceImpl.dao.dms.DMSDeviceLedgerDAO;
import com.iplant.base.po.OutResult;
import com.iplant.base.po.Pagination;
import com.iplant.base.po.enums.DBEnumType;
import com.iplant.base.po.enums.DBSchemas;
import com.iplant.base.po.enums.ExceptionTypes;
import com.iplant.base.utils.cache.CacheUtils;
import com.iplant.base.utils.general.CalendarTool;
import com.iplant.base.utils.general.StringUtils;
import com.iplant.base.utils.sql.BaseDAO;
import com.iplant.basic.service.basicenum.stat.StatTypes;
import com.iplant.basic.service.po.bms.BMSEmployee;
import lombok.extern.slf4j.Slf4j;

import java.util.*;
import java.util.stream.Collectors;


@Slf4j
public class DMSDeviceAlarmDAO extends BaseDAO {

    private static DMSDeviceAlarmDAO Instance = null;

    private DMSDeviceAlarmDAO() {
        super("dms_device_alarm", DBEnumType.MySQL, DBSchemas.AMS);
    }

    public static DMSDeviceAlarmDAO getInstance() {
        if (Instance == null)
            Instance = new DMSDeviceAlarmDAO();
        return Instance;
    }

    private List<DMSDeviceAlarm> DMS_SelectDeviceAlarmList(BMSEmployee wLoginUser, List<Integer> wDeviceIDList, String wDeviceNo, String wDeviceName,
                                                           List<String> wAssetNoList, int wDeviceType, int wModelID, int wFactoryID, int wWorkShopID, int wAreaID,
                                                           String wAlarmCode,int wEventType, int wDataGrad,  int wPositionID, Calendar wStartTime, Calendar wEndTime, Pagination wPagination, OutResult<Integer> wErrorCode) {
        List<DMSDeviceAlarm> wResult = new ArrayList<DMSDeviceAlarm>();
        wErrorCode.set(0);
        try {
            if (wDeviceIDList == null)
                wDeviceIDList = new ArrayList<Integer>();
            wDeviceIDList.removeIf(p -> p <= 0);

            if (wAssetNoList == null)
                wAssetNoList = new ArrayList<String>();
            wAssetNoList.removeIf(p -> StringUtils.isEmpty(p));

            Calendar wBaseTime = CalendarTool.getBasicDate();
            if (wStartTime.compareTo(wBaseTime) < 0)
                wStartTime = wBaseTime;
            if (wEndTime.compareTo(wBaseTime) < 0)
                wEndTime = wBaseTime;
            if (wStartTime.compareTo(wEndTime) > 0) {
                return wResult;
            }

            List<DMSDeviceLedger> wDMSDeviceLedgerList = DMSDeviceLedgerDAO.getInstance().DMS_SelectDeviceLedgerList(wLoginUser, wDeviceIDList, wDeviceNo,
                    wDeviceName, wAssetNoList, wDeviceType, wModelID, wFactoryID, wWorkShopID, wAreaID, 1, wErrorCode);

            if (wErrorCode.Result != 0)
                return wResult;

            if (wDMSDeviceLedgerList == null || wDMSDeviceLedgerList.size() == 0)
                return wResult;

            Map<String, DMSDeviceLedger> wDeviceLedgerMap = wDMSDeviceLedgerList.stream().collect(Collectors.toMap(p -> p.AssetNo, p -> p, (o1, o2) -> o1));

            wAssetNoList = wDeviceLedgerMap.keySet().stream().collect(Collectors.toList());

            List<DMSDeviceHisAlarm> wDMSDeviceHisAlarmList = DMSDeviceHisAlarmDAO.getInstance().DMS_SelectDeviceHisAlarmList(wLoginUser,
                    wAssetNoList, wAlarmCode, wEventType, wDataGrad, wPositionID, wStartTime, wEndTime, wPagination, wErrorCode);
            if (wErrorCode.Result != 0)
                return wResult;

            if (wDMSDeviceHisAlarmList == null || wDMSDeviceHisAlarmList.size() == 0) {
                return wResult;
            }
            DMSDeviceAlarm wDeviceAlarm;
            // wReader\[\"(\w+)\"\]
            for (DMSDeviceHisAlarm wDeviceHisAlarm : wDMSDeviceHisAlarmList) {
                if (wDeviceLedgerMap.containsKey(wDeviceHisAlarm.AssetNo)) {
                    wDeviceAlarm = wDeviceHisAlarm.CreateDeviceAlarm(wDeviceLedgerMap.get(wDeviceHisAlarm.AssetNo));
                } else {
                    wDeviceAlarm = wDeviceHisAlarm.CreateDeviceAlarm(null);
                }
                wResult.add(wDeviceAlarm);
            }

        } catch (Exception e) {
            wErrorCode.Result = ExceptionTypes.DBSQL.getValue();
            log.error("DMS_SelectDeviceAlarmList", e);
        }
        return wResult;
    }

    public List<DMSDeviceAlarm> DMS_CurrentDeviceAlarmList(BMSEmployee wLoginUser, List<Integer> wDeviceIDList,
                                                           String wDeviceNo, String wDeviceName, List<String> wAssetNoList, int wDeviceType, int wModelID,
                                                           int wFactoryID, int wWorkShopID, int wAreaID, String wAlarmCode, int wDataGrad, int wPositionID,Calendar wStartTime, Calendar wEndTime, Pagination wPagination,

                                                           OutResult<Integer> wErrorCode) {
        List<DMSDeviceAlarm> wResult = new ArrayList<DMSDeviceAlarm>();
        wErrorCode.set(0);
        try {
            if (wDeviceIDList == null)
                wDeviceIDList = new ArrayList<Integer>();
            wDeviceIDList.removeIf(p -> p <= 0);

            if (wAssetNoList == null)
                wAssetNoList = new ArrayList<String>();
            wAssetNoList.removeIf(p -> StringUtils.isEmpty(p));


            List<DMSDeviceLedger> wDMSDeviceLedgerList = DMSDeviceLedgerDAO.getInstance().DMS_SelectDeviceLedgerList(wLoginUser, wDeviceIDList, wDeviceNo,
                    wDeviceName, wAssetNoList, wDeviceType, wModelID, wFactoryID, wWorkShopID, wAreaID, 1, wErrorCode);

            if (wErrorCode.Result != 0)
                return wResult;

            if (wDMSDeviceLedgerList == null || wDMSDeviceLedgerList.size() == 0)
                return wResult;

            Map<String, DMSDeviceLedger> wDeviceLedgerMap = wDMSDeviceLedgerList.stream().collect(Collectors.toMap(p -> p.AssetNo, p -> p, (o1, o2) -> o1));

            wAssetNoList = wDeviceLedgerMap.keySet().stream().collect(Collectors.toList());

            List<DMSDeviceCurrentAlarm> wDMSDeviceCurrentAlarmList = DMSDeviceCurrentAlarmDAO.getInstance().DMS_SelectDeviceCurrentAlarmList(wLoginUser,
                    wAssetNoList, wAlarmCode, wDataGrad,wPositionID, wStartTime, wEndTime, wPagination, wErrorCode);
            if (wErrorCode.Result != 0)
                return wResult;

            if (wDMSDeviceCurrentAlarmList == null || wDMSDeviceCurrentAlarmList.size() == 0) {
                return wResult;
            }
            DMSDeviceAlarm wDeviceAlarm;

            for (DMSDeviceCurrentAlarm wDeviceHisAlarm : wDMSDeviceCurrentAlarmList) {
                if (wDeviceLedgerMap.containsKey(wDeviceHisAlarm.AssetNo)) {
                    wDeviceAlarm = wDeviceHisAlarm.CreateDeviceAlarm(wDeviceLedgerMap.get(wDeviceHisAlarm.AssetNo));
                } else {
                    wDeviceAlarm = wDeviceHisAlarm.CreateDeviceAlarm(null);
                }
                wResult.add(wDeviceAlarm);
            }
        } catch (Exception e) {

            wErrorCode.Result = ExceptionTypes.DBSQL.getValue();
            log.error("DMS_CurrentDeviceAlarmList", e);
        }
        return wResult;
    }

    public List<DMSDeviceAlarm> DMS_CurrentDeviceAlarmList(BMSEmployee wLoginUser, List<Integer> wDeviceIDList, List<String> wAssetNoList,
                                                           OutResult<Integer> wErrorCode) {
        return this.DMS_CurrentDeviceAlarmList(wLoginUser, wDeviceIDList, "", "", wAssetNoList,
                -1, -1, -1, -1, -1, "", -1, -1,
                CalendarTool.getBasicDate(), CalendarTool.getBasicDate(), Pagination.getMaxSize(DMSDeviceCurrentAlarm.class), wErrorCode);

    }

    public List<DMSDeviceAlarm> DMS_CurrentDeviceAlarmList(BMSEmployee wLoginUser, int wDeviceID, String wDeviceNo, String wAssetNo,
                                                           OutResult<Integer> wErrorCode) {
        return this.DMS_CurrentDeviceAlarmList(wLoginUser, StringUtils.parseListArgs(wDeviceID), wDeviceNo, "", StringUtils.parseListArgs(wAssetNo),
                -1, -1, -1, -1, -1, "", -1, -1,
                CalendarTool.getBasicDate(), CalendarTool.getBasicDate(), Pagination.getMaxSize(DMSDeviceCurrentAlarm.class), wErrorCode);

    }


    public List<DMSDeviceAlarm> DMS_SelectDeviceAlarmList(BMSEmployee wLoginUser, String wName,
                                                          String wAssetNo, int wDeviceType, int wModelID, int wFactoryID, int wWorkShopID, int wAreaID,
                                                          String wAlarmCode, int wEventType, int wDataGrad,int wPositionID, Calendar wStartTime, Calendar wEndTime, Pagination wPagination,
                                                          OutResult<Integer> wErrorCode) {
        return DMS_SelectDeviceAlarmList(wLoginUser, null, "", wName, StringUtils.parseListArgs(wAssetNo), wDeviceType,
                wModelID, wFactoryID, wWorkShopID, wAreaID, wAlarmCode, wEventType, wDataGrad, wPositionID,wStartTime, wEndTime, wPagination,
                wErrorCode);
    }

    public List<DMSDeviceAlarm> DMS_SelectDeviceAlarmList(BMSEmployee wLoginUser, String wName,
                                                          String wAssetNo, int wDeviceType, int wModelID, int wFactoryID, int wWorkShopID, int wAreaID,
                                                          int wEventType, int wDataGrad,int wPositionID, Calendar wStartTime, Calendar wEndTime, Pagination wPagination,
                                                          OutResult<Integer> wErrorCode) {
        return DMS_SelectDeviceAlarmList(wLoginUser, null, "", wName, StringUtils.parseListArgs(wAssetNo), wDeviceType,
                wModelID, wFactoryID, wWorkShopID, wAreaID, "", wEventType, wDataGrad,wPositionID, wStartTime, wEndTime, wPagination,
                wErrorCode);
    }

    public List<DMSDeviceAlarm> DMS_SelectDeviceAlarm(BMSEmployee wLoginUser, int wID, String wCode, String wAssetNo, String wAlarmCode,
                                                      int wEventType, int wDataGrad,int wPositionID, Calendar wStartTime, Calendar wEndTime, Pagination wPagination,
                                                      OutResult<Integer> wErrorCode) {
        if (wID > 0) {
            return this.DMS_SelectDeviceAlarmList(wLoginUser, StringUtils.parseListArgs(wID), "", "",
                    null, -1, -1, -1, -1, -1, wAlarmCode, wEventType, wDataGrad,wPositionID, wStartTime, wEndTime, wPagination, wErrorCode);
        } else if (StringUtils.isNotEmpty(wCode)) {
            return this.DMS_SelectDeviceAlarmList(wLoginUser, null, wCode, "", null,
                    -1, -1, -1, -1, -1, wAlarmCode, wEventType, wDataGrad,wPositionID, wStartTime, wEndTime, wPagination, wErrorCode);
        } else if (StringUtils.isNotEmpty(wAssetNo)) {
            return this.DMS_SelectDeviceAlarmList(wLoginUser, null, "", "", StringUtils.parseListArgs(wAssetNo),
                    -1, -1, -1, -1, -1, wAlarmCode, wEventType, wDataGrad, wPositionID,wStartTime, wEndTime, wPagination, wErrorCode);
        }
        return new ArrayList<DMSDeviceAlarm>();
    }

    public List<DMSDeviceAlarm> DMS_SelectDeviceAlarmList(BMSEmployee wLoginUser, List<Integer> wDeviceIDList, String wAlarmCode, int wEventType, int wDataGrad,int wPositionID,  Calendar wStartTime, Calendar wEndTime, Pagination wPagination,
                                                          OutResult<Integer> wErrorCode) {
        return this.DMS_SelectDeviceAlarmList(wLoginUser, wDeviceIDList, "", "", null,
                -1, -1, -1, -1, -1, wAlarmCode, wEventType, wDataGrad, wPositionID,wStartTime, wEndTime, wPagination, wErrorCode);
    }


    public List<DMSDeviceAlarmStatistics> DMS_SelectDeviceAlarmStatisticsList(BMSEmployee wLoginUser, List<Integer> wDeviceIDList,
                                                                              StatTypes wShiftPeriod, Calendar wStartTime, Calendar wEndTime,
                                                                              OutResult<Integer> wErrorCode) {

        List<DMSDeviceAlarmStatistics> wResult = new ArrayList<DMSDeviceAlarmStatistics>();
        try {

            wErrorCode.set(0);
            String wInstance = getDBName();
            if (wErrorCode.Result != 0)
                return wResult;

            String wSqlFormatDate = "'%Y-%m-%d'";

            switch (wShiftPeriod) {
                case Day:
                    wSqlFormatDate = "'%Y-%m-%d'";
                    break;
                case Week:
                    wSqlFormatDate = "'%Y-%m-%u'";
                    break;
                case Month:
                    wSqlFormatDate = "'%Y-%m'";
                    break;
                case Year:
                    wSqlFormatDate = "'%Y'";
                    break;
                case Default:
                    wSqlFormatDate = "'%Y-%m-%d'";
                    break;
                default:
                    break;

            }


            String wSQL = StringUtils.Format("select t.ID as DeviceID, t.AssetNo, date_format(t1.OccurTime,{1}) as AlarmTime, " +
                            " Count(t1.DeviceID) as AlarmCount,  sum((t1.UpdateDate - t1.OccurTime) / 1000) as AlarmDuration" +
                            " from {0}.dms_device_hisalarm t1  inner  join {0}.dms_device_ledger t on t.AssetNo = t1.DeviceID " +
                            " where ( :wDeviceIDList = '''' or t.ID IN({2}))   " +
                            " and ( :wStartTime <= str_to_date(''2010-01-01'', ''%Y-%m-%d'')  or :wStartTime <= t1.UpdateDate) " +
                            " and ( :wEndTime <= str_to_date(''2010-01-01'', ''%Y-%m-%d'') or :wEndTime >= t1.OccurTime)  " +
                            " group by t.ID, date_format(t1.OccurTime, {1})"
                    , wInstance, wSqlFormatDate, wDeviceIDList.size() > 0 ? StringUtils.Join(",", wDeviceIDList) : "0");
            wSQL = this.DMLChange(wSQL);
            Map<String, Object> wParamMap = new HashMap<String, Object>();
            wParamMap.put("wDeviceIDList", StringUtils.Join(",", wDeviceIDList));
            wParamMap.put("wStartTime", wStartTime);
            wParamMap.put("wEndTime", wEndTime);
            List<Map<String, Object>> wQueryResult = this.queryForList(wSQL, wParamMap);

            for (Map<String, Object> wReader : wQueryResult) {
                DMSDeviceAlarmStatistics wDeviceAlarmStatistics = new DMSDeviceAlarmStatistics();
                wDeviceAlarmStatistics.DeviceID = StringUtils.parseInt(wReader.get("DeviceID"));
                wDeviceAlarmStatistics.AssetNo = StringUtils.parseString(wReader.get("AssetNo"));
                wDeviceAlarmStatistics.AlarmTime = StringUtils.parseCalendar(wReader.get("AlarmTime"));
                wDeviceAlarmStatistics.AlarmCount = StringUtils.parseInt(wReader.get("AlarmCount"));
                wDeviceAlarmStatistics.AlarmDuration = StringUtils.parseDouble(wReader.get("AlarmDuration"));
                wResult.add(wDeviceAlarmStatistics);
            }

        } catch (Exception e) {

            wErrorCode.Result = ExceptionTypes.DBSQL.getValue();
            log.error("DMS_SelectDeviceAlarmStatisticsList", e);
        }
        return wResult;


    }


    public List<DMSDeviceAlarmFrequency> DMS_SelectDeviceAlarmFrequencyList(BMSEmployee wLoginUser, List<Integer> wDeviceIDList, Calendar wStartTime, Calendar wEndTime,
                                                                            OutResult<Integer> wErrorCode) {

        List<DMSDeviceAlarmFrequency> wResult = new ArrayList<DMSDeviceAlarmFrequency>();
        try {

            wErrorCode.set(0);
            String wInstance = getDBName();
            if (wErrorCode.Result != 0)
                return wResult;


            String wSQL = StringUtils.Format(" select  t1.Name as AlarmName,t1.Code as AlarmCode, t1.ParameterDesc as AlarmDesc, " +
                            " count( case when t.EventType=1 then t.FaultID  else null end ) as AlarmCount, " +
                            " count( case when t.EventType=2 then t.FaultID  else null end ) as AlarmEndCount  from {0}.dms_device_hisalarm t  " +
                            " inner join {0}.dms_device_ledger p on p.AssetNo = t.DeviceID " +
                            " inner join {0}.dms_device_parameter t1 on t1.Code = t.FaultID   and p.ID = t1.DeviceID " +
                            " where ( :wDeviceIDList = '''' or p.ID IN({1}))  " +
                            " and ( :wStartTime <= str_to_date(''2010-01-01'', ''%Y-%m-%d'')  or :wStartTime <= t.UpdateDate) " +
                            " and ( :wEndTime <= str_to_date(''2010-01-01'', ''%Y-%m-%d'') or :wEndTime >= t.UpdateDate)  " +
                            " group by t1.Name "

                    , wInstance, wDeviceIDList.size() > 0 ? StringUtils.Join(",", wDeviceIDList) : "0");
            wSQL = this.DMLChange(wSQL);
            Map<String, Object> wParamMap = new HashMap<String, Object>();
            wParamMap.put("wDeviceIDList", StringUtils.Join(",", wDeviceIDList));
            wParamMap.put("wStartTime", wStartTime);
            wParamMap.put("wEndTime", wEndTime);
            List<Map<String, Object>> wQueryResult = this.queryForList(wSQL, wParamMap);

            int wAlarmEndCount = 0;

            for (Map<String, Object> wReader : wQueryResult) {
                DMSDeviceAlarmFrequency wDeviceAlarmFrequency = new DMSDeviceAlarmFrequency();
                wDeviceAlarmFrequency.AlarmCode = StringUtils.parseString(wReader.get("AlarmCode"));
                wDeviceAlarmFrequency.AlarmName = StringUtils.parseString(wReader.get("AlarmName"));
                wDeviceAlarmFrequency.AlarmDesc = StringUtils.parseString(wReader.get("AlarmDesc"));
                wDeviceAlarmFrequency.AlarmCount = StringUtils.parseInt(wReader.get("AlarmCount"));

                wAlarmEndCount = StringUtils.parseInt(wReader.get("AlarmEndCount"));
                if (wAlarmEndCount > wDeviceAlarmFrequency.AlarmCount)
                    wDeviceAlarmFrequency.AlarmCount = wAlarmEndCount;
                wResult.add(wDeviceAlarmFrequency);
            }

        } catch (Exception e) {

            wErrorCode.Result = ExceptionTypes.DBSQL.getValue();
            log.error("DMS_SelectDeviceAlarmFrequencyList", e);
        }
        return wResult;


    }


    public List<String> DMS_CloseAlarmHistoryString(Collection<DMSDeviceAlarm> wDMSDeviceAlarmList) {
        //添加EventType=2
        List<String> wResult = new ArrayList<String>();
        if (wDMSDeviceAlarmList == null || wDMSDeviceAlarmList.size() == 0)
            return wResult;

        for (DMSDeviceAlarm wDMSDeviceAlarm : wDMSDeviceAlarmList) {
            if (wDMSDeviceAlarm == null || StringUtils.isEmpty(wDMSDeviceAlarm.AlarmCode) || StringUtils.isEmpty(wDMSDeviceAlarm.AssetNo))
                continue;


            wResult.add(StringUtils.Format(" Insert into {0}.dms_device_hisalarm (DeviceID,OccurTime,FaultID,UpdateDate,EventType) " +
                            "values ({1},''{2}'',''{3}'',now(),2);", getDBName(), wDMSDeviceAlarm.AssetNo,
                    StringUtils.parseCalendarToString(wDMSDeviceAlarm.StatusTime, "yyyy-MM-dd HH:mm:ss"), wDMSDeviceAlarm.AlarmCode));
        }
        return wResult;
    }

    public List<String> DMS_AddAlarmHistoryString(Collection<DMSDeviceAlarm> wDMSDeviceAlarmList) {
        //添加EventType=2
        List<String> wResult = new ArrayList<String>();
        if (wDMSDeviceAlarmList == null || wDMSDeviceAlarmList.size() == 0)
            return wResult;

        for (DMSDeviceAlarm wDMSDeviceAlarm : wDMSDeviceAlarmList) {
            if (wDMSDeviceAlarm == null || StringUtils.isEmpty(wDMSDeviceAlarm.AlarmCode) || StringUtils.isEmpty(wDMSDeviceAlarm.AssetNo))
                continue;


            wResult.add(StringUtils.Format(" Insert into {0}.dms_device_hisalarm (DeviceID,OccurTime,FaultID,UpdateDate,EventType) " +
                            "values ({1},''{2}'',''{3}'',''{4}'',2);", getDBName(), wDMSDeviceAlarm.AssetNo,
                    StringUtils.parseCalendarToString(wDMSDeviceAlarm.StatusTime, "yyyy-MM-dd HH:mm:ss"), wDMSDeviceAlarm.AlarmCode,
                    StringUtils.parseCalendarToString(wDMSDeviceAlarm.StatusTimeEnd, "yyyy-MM-dd HH:mm:ss")));
        }
        return wResult;
    }


    public List<String> DMS_CloseAlarmHistoryString(DMSDeviceAlarm wDMSDeviceAlarm) {
        List<String> wSqlList = new ArrayList<String>();
        //添加EventType=2
        if (wDMSDeviceAlarm == null || StringUtils.isEmpty(wDMSDeviceAlarm.AlarmCode) || StringUtils.isEmpty(wDMSDeviceAlarm.AssetNo))
            return wSqlList;


        if (wDMSDeviceAlarm.StatusTime.compareTo(CalendarTool.getBasicDate()) <= 0) {
            wSqlList.add(StringUtils.Format(" Insert into {0}.dms_device_hisalarm (DeviceID,OccurTime,FaultID,UpdateDate,EventType) " +
                            " select {1},OccurTime,''{2}'',now(),2 from dms_device_alarm where DeviceID={1} AND FaultID=''{2}'' ;", getDBName(), wDMSDeviceAlarm.AssetNo,
                    wDMSDeviceAlarm.AlarmCode));
        } else {
            wSqlList.add(StringUtils.Format("  Insert into {0}.dms_device_hisalarm (DeviceID,OccurTime,FaultID,UpdateDate,EventType) " +
                            "values ({1},''{2}'',''{3}'',now(),2);", getDBName(), wDMSDeviceAlarm.AssetNo,
                    StringUtils.parseCalendarToString(wDMSDeviceAlarm.StatusTime, "yyyy-MM-dd HH:mm:ss"), wDMSDeviceAlarm.AlarmCode));
        }

        wSqlList.add(StringUtils.Format("delete from {0}.dms_device_hisalarm where DeviceID={1} AND FaultID=''{2}'' and EventType=1 ", getDBName(), wDMSDeviceAlarm.AssetNo, wDMSDeviceAlarm.AlarmCode));
        return wSqlList;
    }

    public List<String> DMS_CloseAlarmCodeHistoryString(String wAssetNo) {
        List<String> wSqlList = new ArrayList<String>();
        //添加EventType=2
        if (StringUtils.isEmpty(wAssetNo))
            return wSqlList;


        wSqlList.add(StringUtils.Format("delete from {0}.dms_device_hisalarm where DeviceID={1} AND  EventType=1 ", getDBName(), wAssetNo));


        wSqlList.add(StringUtils.Format(" Insert into {0}.dms_device_hisalarm (DeviceID,OccurTime,FaultID,UpdateDate,EventType) " +
                " select {1},OccurTime,FaultID,now(),2 from dms_device_alarm where DeviceID={1} AND IsCode=1 ;", getDBName(), wAssetNo));

        return wSqlList;
    }

    public List<String> DMS_CloseAlarmAll(String wAssetNo) {
        List<String> wResult = new ArrayList<String>();
        //添加EventType=2
        if (StringUtils.isEmpty(wAssetNo))
            return wResult;

        wResult.add(StringUtils.Format(" Insert into {0}.dms_device_hisalarm (DeviceID,OccurTime,FaultID,UpdateDate,EventType) " +
                " select {1},OccurTime,FaultID,now(),2 from dms_device_alarm where DeviceID={1}  ;", getDBName(), wAssetNo));


        wResult.add(StringUtils.Format(" delete From {0}.dms_device_alarm where DeviceID={1}  ;", getDBName(), wAssetNo));

        return wResult;
    }


    public List<String> DMS_InsertAlarmHistoryString(Collection<DMSDeviceAlarm> wDMSDeviceAlarmList) {
        //添加EventType=1
        List<String> wResult = new ArrayList<String>();
        if (wDMSDeviceAlarmList == null || wDMSDeviceAlarmList.size() == 0)
            return wResult;

        for (DMSDeviceAlarm wDMSDeviceAlarm : wDMSDeviceAlarmList) {
            if (wDMSDeviceAlarm == null || StringUtils.isEmpty(wDMSDeviceAlarm.AlarmCode) || StringUtils.isEmpty(wDMSDeviceAlarm.AssetNo))
                continue;

            wResult.add(StringUtils.Format(" Insert into {0}.dms_device_hisalarm (DeviceID,OccurTime,FaultID,UpdateDate,EventType) " +
                            "values ({1},''{2}'',''{3}'',''{2}'',1);", getDBName(), wDMSDeviceAlarm.AssetNo,
                    StringUtils.parseCalendarToString(wDMSDeviceAlarm.StatusTime, "yyyy-MM-dd HH:mm:ss"), wDMSDeviceAlarm.AlarmCode));
        }
        return wResult;
    }

    public String DMS_InsertAlarmHistoryString(DMSDeviceAlarm wDMSDeviceAlarm) {
        if (wDMSDeviceAlarm == null || StringUtils.isEmpty(wDMSDeviceAlarm.AlarmCode) || StringUtils.isEmpty(wDMSDeviceAlarm.AssetNo))
            return "";

        return StringUtils.Format(" Insert into {0}.dms_device_hisalarm (DeviceID,OccurTime,FaultID,UpdateDate,EventType) " +
                        "values ({1},''{2}'',''{3}'',''{2}'',1);", getDBName(), wDMSDeviceAlarm.AssetNo,
                StringUtils.parseCalendarToString(wDMSDeviceAlarm.StatusTime, "yyyy-MM-dd HH:mm:ss"), wDMSDeviceAlarm.AlarmCode);
    }

    public String DMS_DeleteAlarmString(List<String> wAssetNoList) {
        if (wAssetNoList == null || wAssetNoList.size() == 0)
            return "";
        return StringUtils.Format("delete from {0}.dms_device_alarm where Device in (''{1}'') ;", getDBName(), StringUtils.Join("','", wAssetNoList));
    }

    public String DMS_DeleteAlarmString(String wAssetNo) {
        if (StringUtils.isEmpty(wAssetNo))
            return "";
        return StringUtils.Format("delete from {0}.dms_device_alarm where DeviceID =''{1}'' ;",
                getDBName(), wAssetNo);
    }

    public String DMS_DeleteAlarmString(String wAssetNo, String wAlarmCode) {
        if (StringUtils.isEmpty(wAssetNo) || StringUtils.isEmpty(wAlarmCode))
            return "";
        return StringUtils.Format("delete from {0}.dms_device_alarm where DeviceID =''{1}'' and FaultID = ''{2}'';  ",
                getDBName(), wAssetNo, wAlarmCode);
    }


    public int DMS_DeleteCurrentAlarm(String wAssetNo, String wAlarmCode) {
        int wRowChange = 0;
        if (StringUtils.isEmpty(wAssetNo) || StringUtils.isEmpty(wAlarmCode))
            return wRowChange;
        try {
            String wSQL = StringUtils.Format("delete from {0}.dms_device_alarm where DeviceID =''{1}'' and FaultID = ''{2}'';  ",
                    getDBName(), wAssetNo, wAlarmCode);
            wRowChange = this.update(wSQL, new HashMap<>());
        } catch (Exception ex) {
            log.error("DMS_DeleteCurrentAlarm", ex);
        }
        return wRowChange;
    }


    public String DMS_DeleteAlarmCodeString(String wAssetNo) {
        if (StringUtils.isEmpty(wAssetNo))
            return "";
        return StringUtils.Format("delete from {0}.dms_device_alarm where DeviceID =''{1}'' and IsCode = 1;  ",
                getDBName(), wAssetNo);
    }

    public List<String> DMS_InsertCurrentAlarmString(List<DMSDeviceAlarm> wDMSDeviceAlarmList) {
        List<String> wResult = new ArrayList<String>();
        if (wDMSDeviceAlarmList == null || wDMSDeviceAlarmList.size() == 0)
            return wResult;

        for (DMSDeviceAlarm wDMSDeviceAlarm : wDMSDeviceAlarmList) {
            if (wDMSDeviceAlarm == null || StringUtils.isEmpty(wDMSDeviceAlarm.AlarmCode) || StringUtils.isEmpty(wDMSDeviceAlarm.AssetNo))
                continue;
            wResult.add(StringUtils.Format(" Insert into {0}.dms_device_alarm (DeviceID,OccurTime,FaultID,UpdateDate) " +
                            "values ({1},''{2}'',''{3}'',''{2}'');", getDBName(), wDMSDeviceAlarm.AssetNo,
                    StringUtils.parseCalendarToString(wDMSDeviceAlarm.StatusTime, "yyyy-MM-dd HH:mm:ss"), wDMSDeviceAlarm.AlarmCode));
        }

        return wResult;
    }

    public String DMS_InsertCurrentAlarmString(DMSDeviceAlarm wDMSDeviceAlarm, int wIsCode) {
        if (wDMSDeviceAlarm == null || StringUtils.isEmpty(wDMSDeviceAlarm.AlarmCode) || StringUtils.isEmpty(wDMSDeviceAlarm.AssetNo))
            return "";

        return StringUtils.Format(" Insert into {0}.dms_device_alarm (DeviceID,OccurTime,FaultID,UpdateDate,IsCode) " +
                        "values ({1},''{2}'',''{3}'',''{2}'',{4});", getDBName(), wDMSDeviceAlarm.AssetNo,
                StringUtils.parseCalendarToString(wDMSDeviceAlarm.StatusTime, "yyyy-MM-dd HH:mm:ss"), wDMSDeviceAlarm.AlarmCode, wIsCode);

    }


}
